<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片列表 -->
    <el-card>
      <el-row>
        <el-col :span="6">
          <el-button type="primary" plain @click="showAddCate">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 渲染数据表格 -->
      <tree-table
        :data="categoryList"
        :columns="columns"
        :show-index="true"
        index-text="#"
        :selection-type="false"
        :expand-type="false"
        border
      >
        <template slot="isok" slot-scope="scope">
          <i
            style="color: lightgreen"
            v-if="scope.row.cat_deleted === false"
            class="el-icon-success"
          ></i>
          <i style="color: lightgreen" class="el-icon-error" v-else></i>
        </template>
        <template slot="order" slot-scope="scope">
          <!-- {{scope.row}} -->
          <el-tag v-if="scope.row.cat_level === 0" type="primary">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="option" slot-scope="scope">
          <!-- {{scope.row}} -->
          <el-button
            plain
            size="mini"
            type="warning"
            icon="el-icon-edit"
            @click="editCate(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            plain
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeCate(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>

      <!-- 添加分页对话框 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20, 25]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="50%" @close="addCateClear">
      <!-- 表单验证 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectKeys"
            :options="parentList"
            :props="cateProps"
            @change="selectParentCate"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateHandle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateClear"
    >
      <!-- 分类名称 -->
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 定义一个商品分类数据接收
      categoryList: [],

      // 请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },

      // 总数
      total: 0,

      // 配置columns 表格各列的配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          headerAlign: 'center',
          align: 'center'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok',
          headerAlign: 'center',
          align: 'center'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
          headerAlign: 'center',
          align: 'center'
        },
        {
          label: '操作',
          type: 'template',
          template: 'option',
          headerAlign: 'center',
          align: 'center'
        }
      ],

      // 定义添加对话框的默认显示和隐藏
      addCateDialogVisible: false,

      // 定义添加分类的绑定数据表单对象
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },

      // 添加分类验证规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },

      // 接收父级数据的数组
      parentList: [],

      // prop参数的配置选项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover'
      },

      // v-model的默认的级联选择器选中的值
      selectKeys: [],

      // 编辑功能对话框默认显示和隐藏
      editCateDialogVisible: false,

      // 定义一个编辑功能接收的数据
      editCateForm: {},

      // 定义一个验证规则
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCategoryList()
  },
  methods: {
    // 获取后台数据
    async getCategoryList () {
      const { data: res } = await this.$http.get('/categories', { params: this.queryInfo })
      // 如果错误 返回后台数据
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功之后 先赋值
      // console.log(res)
      this.categoryList = res.data.result
      this.total = res.data.total
    },

    // 监听分页中显示的每页的数据条数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCategoryList()
    },

    // 监听分页中显示当前的页码
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCategoryList()
    },

    // 点击确定展示对话框
    showAddCate () {
      this.addCateDialogVisible = true
      // 调用获取父级数据的方法
      this.getParentList()
    },

    // 获取父级数据的方法
    async getParentList () {
      const { data: res } = await this.$http.get('/categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.parentList = res.data
      console.log(res.data)
    },

    // 选中级联选择器触发
    selectParentCate () {
      console.log(this.selectKeys)
      // 如果输入的selectKeys长度是大于0 来获取id和等级
      if (this.selectKeys.length > 0) {
        //   // 取到父级的id
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        //   // 取到等级
        this.addCateForm.cat_level = this.selectKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 点击确定提交
    addCateHandle () {
      // console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/categories', this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCategoryList()
        // this.getParentList()
        this.addCateDialogVisible = false
      })
    },

    // 关闭对话框重置表单
    addCateClear () {
      this.$refs.addCateFormRef.resetFields()
      // 重置父级分类
      this.selectKeys = []
      // 重置父级等级和父级分类
      this.addCateForm.cat_pid = this.addCateForm.cat_level = 0
    },

    // 点击编辑按钮触发事件 先根据id获取数据并赋值
    async editCate (id) {
      // console.log(id)
      const { data: res } = await this.$http.get(`/categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editCateForm = res.data
      console.log(res.data)
      this.editCateDialogVisible = true
    },

    // 关闭对话框 清空表单
    editCateClear () {
      this.$refs.editCateFormRef.resetFields()
    },

    // 点击确定 更改请求 先进行验证
    allotCate () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`/categories/${this.editCateForm.cat_id}`, {
          cat_name: this.editCateForm.cat_name
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCategoryList()
        this.editCateDialogVisible = false
      })
    },

    // 点击删除
    async removeCate (id) {
      console.log(id)
      const removeCateResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeCateResult !== 'confirm') return this.$message.info('您取消了删除!')
      const { data: res } = await this.$http.delete(`/categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getCategoryList()
    }
  }
}
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 20px;
}

.el-cascader {
  width: 100%;
}
</style>
